package com.estudioskelon.lorenzonebromanuelalejandro;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Toast;

public class Scenario extends View {

	Canvas canvas;
	ArrayList<Car> cars;
	Frog frog;
	final int numberOfCars = 10;
	View colision;
	
	public Scenario(Context context, AttributeSet attrs) {
		super(context, attrs);
		cars = new ArrayList();
		frog = new Frog(this);
	}

	@Override
	protected void onSizeChanged(int ancho, int alto, int ancho_anterior,
			int alto_anterior) {
	}
	
	public void createNewCar(){
		if (cars.size() < numberOfCars){
			cars.add(new Car(this));
			System.out.println(cars.size());
		}
	}

	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		this.canvas = canvas;
		createNewCar();
		moveFrog();
		checkCollision();
		moveCars();
		checkCars(canvas);
		checkCollision();
	}
	
	public void checkCars(Canvas canvas){
		for (int i = 0; i < cars.size(); i++){
			if (cars.get(i).isOut(canvas))
				cars.remove(i);
		}
	}
	
	public void leapFrog(){
		frog.leap();
	}
	
	public void moveFrog(){
		if (!frog.hasArrived())
		frog.move();
		frog.draw(canvas);
	}
	
	public void moveCars(){
		for (Car car: cars){
			car.drive(getScenarioWidth(), getScenarioHeight());
			car.draw(canvas);
		}
	}
	
	public void checkCollision(){
		for (Car car: cars){
			if (car.getRect().contains(frog.getRect())){
				stopAllCars();
				toast("The frog has been squashed.");
			}
		}
	}
	
	public void stopAllCars(){
		for (Car car: cars){
			car.stop();
		}
	}
	
    private void toast(String text) {
    	Toast toast = Toast.makeText(getContext(), text, Toast.LENGTH_SHORT);
    	toast.show();
    }
	
	public int getScenarioWidth(){
		return canvas.getWidth();
	}
	
	public int getScenarioHeight(){
		return canvas.getHeight();
	}
}
